package edu.nf.computer.admin.controller.handler;/*
 *
 * @Date 2023-06-19
 */

import com.google.gson.GsonBuilder;
import edu.nf.computer.admin.vo.ResultVO;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

public class HandleException {
    /**
     * 全局异常处理
     *
     * @param resp
     * @param e
     * @throws IOException
     */
    public static void handleException(HttpServletResponse resp, Exception e)
            throws IOException {
        ResultVO resultVO = new ResultVO();
        resultVO.setCode(500);
        resultVO.setMsg(e.getMessage());
        print(resp, resultVO);
    }

    /**
     * 响应消息到客户端浏览器
     *
     * @param resp
     * @param responseData
     * @throws IOException
     */
    private static void print(HttpServletResponse resp, ResultVO responseData)
            throws IOException {
        resp.setCharacterEncoding("UTF-8");
        resp.setContentType("application/json;charset=UTF-8");
        PrintWriter out = resp.getWriter();
        out.print(new GsonBuilder()
                .setDateFormat("yyyy-MM-dd hh:mm:ss.SSS")
                .create()
                .toJson(responseData));
        out.flush();
        out.close();
    }
}
